package com.example.douyin.music;
import android.content.ContentResolver;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.example.douyin.R;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class LocalFragment extends Fragment {
    ImageView lastIV,nextIV,playIv;
    TextView titleTv,singerTv;
    ListView musicLv;
    List<MusicBean>list = new ArrayList<>();     // 数据源
    private MusicAdapter adapter;
    int currentPlayPos = 0;    //正在播放音乐的位置
    MediaPlayer mediaPlayer;   //多媒体播放器
    int songPausePos = 0;    //歌曲暂停的位置
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view =  inflater.inflate(R.layout.fragment_local, container, false);
        initView(view);
        mediaPlayer = new MediaPlayer(); //初始化多媒体播放器
        adapter = new MusicAdapter(getContext(), list);
        musicLv.setAdapter(adapter);
        //加载本地数据
        loadData();
        setItemClick();
        return view;
    }
    /* 设置listview每一条的点击事件*/
    private void setItemClick() {
        musicLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                currentPlayPos = position;   // 保存当前播放的位置
                MusicBean musicBean = list.get(position);   //获取正在点击的位置的数据信息
                playMusicInMusicBean(musicBean);
            }
        });
    }
    /* 播放指定对象的音乐信息
     * 1.先停止上一次播放的信息
     * */
    private void playMusicInMusicBean(MusicBean musicBean) {
        singerTv.setText(musicBean.getSinger());
        titleTv.setText(musicBean.getTitle());
        stopMusic();  //停止播放
        mediaPlayer.reset();   //重置多媒体播放器
        try {
            mediaPlayer.setDataSource(musicBean.getPath());
            //开始播放
            playMusic();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /*播放音乐有两种情况： 1.从暂停到播放  2.从停止到播放*/
    private void playMusic() throws IOException {
        if (mediaPlayer!=null&&!mediaPlayer.isPlaying()) {
            if (songPausePos == 0) {   //从停止到播放的
                mediaPlayer.prepare();  //缓存，准备
                mediaPlayer.start();   //开始播放
            }else{    //从暂停到播放
                mediaPlayer.seekTo(songPausePos);
                mediaPlayer.start();
            }
            playIv.setImageResource(R.mipmap.icon_pause);
        }
    }
    //    暂停播放音乐
    private void pauseMusic(){
        if (mediaPlayer!=null && mediaPlayer.isPlaying()) {
            // 获取音乐播放的位置
            songPausePos = mediaPlayer.getCurrentPosition();
            mediaPlayer.pause();
            playIv.setImageResource(R.mipmap.icon_play);
        }
    }

    /* 停止音乐播放*/
    private void stopMusic() {
        if (mediaPlayer!=null) {
            songPausePos = 0;
            mediaPlayer.pause();
            mediaPlayer.seekTo(0);
            mediaPlayer.stop();
            playIv.setImageResource(R.mipmap.icon_play);
        }
    }

    /* 获取内存音乐文件*/
    private void loadData() {
//        1.获取内容接受者对象
        ContentResolver resolver = getContext().getContentResolver();
//        2.获取查询地址
        Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
//        3.开始查找
        Cursor cursor = resolver.query(uri, null, null, null, null);
//        4.遍历游标
        int id = 1;
        SimpleDateFormat sdf = new SimpleDateFormat("mm:ss");
        while (cursor.moveToNext()) {
            String title = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
            String singer = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
            String album = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM));
            String idStr = id+"";
            id++;
            String path = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
            long lt = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION));  //得到一共有多少秒
            Date date = new Date(lt);
            String time = sdf.format(date);
            MusicBean bean = new MusicBean(idStr, title, singer, album, time, path);
            list.add(bean);
        }
        adapter.notifyDataSetChanged();  //数据源发生改变，提示适配器更新
    }

    /* 初始化控件*/
    private void initView(View view) {
        lastIV = view.findViewById(R.id.local_iv_last);
        nextIV = view.findViewById(R.id.local_iv_next);
        playIv = view.findViewById(R.id.local_iv_play);
        titleTv = view.findViewById(R.id.local_tv_title);
        singerTv = view.findViewById(R.id.local_tv_singer);
        musicLv = view.findViewById(R.id.local_lv);
        lastIV.setOnClickListener(listener);
        nextIV.setOnClickListener(listener);
        playIv.setOnClickListener(listener);
    }
    //     声明点击事件的对象
    View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.local_iv_last:   //上一曲
                    if (currentPlayPos==0) {
                        Toast.makeText(getActivity(),"已经是第一曲了，没有上一曲！",Toast.LENGTH_SHORT).show();
                        return;
                    }
                    currentPlayPos = currentPlayPos-1;
                    MusicBean lastMusic = list.get(currentPlayPos);
                    playMusicInMusicBean(lastMusic);
                    break;
                case R.id.local_iv_next:   // 下一曲
                    if (currentPlayPos == list.size()-1) {
                        Toast.makeText(getActivity(),"已经是最后一曲了，没有下一曲！",Toast.LENGTH_SHORT).show();
                        return;
                    }
                    currentPlayPos+=1;
                    MusicBean nextBean = list.get(currentPlayPos);
                    playMusicInMusicBean(nextBean);
                    break;
                case R.id.local_iv_play:   // 播放或暂停
                    if (mediaPlayer.isPlaying()) {
                        pauseMusic();
                    }else{
                        try {
                            playMusic();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    break;
            }
        }
    };
}